//
//      Copyright 2011 richard collins
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

#include "common.h"
#include "display1602.h"

static u8 mode;	//0 == 4bit, 8 == 8bit.

static void WriteCommand (char com)
{
	PORTF &= ~ (1 <<1);
	PORTF &= ~ (1 <<2);
	PORTF |= (1 <<3);
	PORTA = com;
	delay_ms(1);
	PORTF &= ~ (1 <<3) ;
}

static void WriteData (char data)
{
	PORTF |= (1 <<1);
	PORTF &= ~ (1 <<2);
	PORTF |= (1 <<3);
	PORTA = data;
	delay_ms(1);
	PORTF &= ~ (1 <<3) ;
}

void Display1602_Open(u8 _8BitMode)
{
	mode = _8BitMode;

	//Setup
	PORTA = 0xFF; // Turn all off
	DDRA = 0xFF; // direction output
	PORTF = 0xFF; // Turn all off
	DDRF = 0xFF; // direction output

	WriteCommand (0x38); // display mode settings
	delay_ms (1);
	WriteCommand (0x08); // display off
	delay_ms (1);
	WriteCommand (0x01); // clear the screen display
	delay_ms (1);
	WriteCommand (0x06); // display cursor set
	delay_ms (1);
	WriteCommand (0x0C); // Display the open and set the cursor
	delay_ms (1);
	WriteCommand(0x44);
	delay_ms (1);
}

void Display1602_Print(const char *text)
{
	u8 n = 16;
	while (*text && n--)
	{
		WriteData (*text);
		text++;
	}
}

void Display1602_SetXY(u8 x,u8 y)
{
	if (y == 0)
	{
		WriteCommand (0x80 | x);
	}
	else
	{
		WriteCommand (0xC0 | x);
	}
}


void Display1602_Clear()
{
	WriteCommand (0x01);
	delay_ms (1);
}
